#include "customerui.h"
#include "constants.h"
#include <QApplication>
#include <QSplitter>
#include <QDesktopWidget>
#include <QDebug>
#include <QFile>
#include <cmath>

// 使用命名空间
using namespace RestaurantSystem;

CustomerMenuUI::CustomerMenuUI(QWidget *parent)
    : QWidget(parent)
    , m_menuManager(nullptr)
    , m_currentUserId(-1)
    , m_mainLayout(nullptr)
    , m_searchLayout(nullptr)
    , m_searchEdit(nullptr)
    , m_searchButton(nullptr)
    , m_clearButton(nullptr)
    , m_filterLayout(nullptr)
    , m_categoryCombo(nullptr)
    , m_sortCombo(nullptr)
    , m_resultLabel(nullptr)
    , m_scrollArea(nullptr)
    , m_menuContainer(nullptr)
    , m_menuLayout(nullptr)
    , m_paginationLayout(nullptr)
    , m_prevButton(nullptr)
    , m_nextButton(nullptr)
    , m_pageLabel(nullptr)
    , m_pageSizeCombo(nullptr)
    , m_currentPage(1)
    , m_pageSize(12)
    , m_totalPages(1)
    , m_currentCategory("全部")
    , m_currentSortOrder("默认")
    , m_loadingBar(nullptr)
    , m_loadingLabel(nullptr)
{
    try {
        // 初始化界面
        initializeUI();
        
        // 应用样式
        applyStyleSheet();
    } catch (const std::exception &e) {
        // 构造函数异常处理
    } catch (...) {
        // 构造函数未知异常处理
    }
}

CustomerMenuUI::~CustomerMenuUI()
{
    // Qt会自动清理子对象
}

void CustomerMenuUI::setMenuManager(MenuManager *menuManager)
{
    m_menuManager = menuManager;
    
    if (!menuManager) {
        return;
    }
    
    try {
        // 连接库存更新信号
        connect(m_menuManager, &MenuManager::stockUpdated,
                this, &CustomerMenuUI::onStockUpdated);
        
        // 连接菜单项更新信号
        connect(m_menuManager, &MenuManager::menuItemUpdated,
                this, &CustomerMenuUI::onMenuItemUpdated);
        
        // 连接分类变更信号
        connect(m_menuManager, &MenuManager::categoriesChanged,
                this, &CustomerMenuUI::onCategoriesChanged);
        qDebug() << "CustomerMenuUI: Connected to MenuManager categoriesChanged signal";
        
        // 延迟连接DataManager的外部文件变更信号，避免初始化冲突
        QTimer::singleShot(100, this, [this]() {
            connect(&DataManager::instance(), &DataManager::externalFileChanged,
                    this, &CustomerMenuUI::onExternalFileChanged);
            qDebug() << "CustomerMenuUI: Connected to DataManager externalFileChanged signal";
        });
        
        // 延迟加载菜单数据，避免在信号连接过程中引起死锁
        QTimer::singleShot(0, this, &CustomerMenuUI::refreshMenuData);
    } catch (const std::exception &e) {
        // setMenuManager异常处理
    } catch (...) {
        // setMenuManager未知异常处理
    }
}

void CustomerMenuUI::refreshMenuData()
{
    if (!m_menuManager) {
        return;
    }
    
    // 确保UI组件已经初始化，显示加载状态
    if (m_loadingBar) {
        m_loadingBar->setVisible(true);
        m_loadingBar->setRange(0, 0); // 无限进度条
    }
    if (m_loadingLabel) {
        m_loadingLabel->setText("正在加载菜单数据...");
        m_loadingLabel->setVisible(true);
    }
    
    // 禁用界面
    setUIEnabled(false);
    
    try {
        // 获取所有菜单项
        m_allMenuItems = m_menuManager->getAllMenuItems();
        
        
        // 获取分类列表（直接从MenuManager获取所有分类，包括空分类）
        QStringList allCategories = m_menuManager->getAllCategories();
        m_categories.clear();
        m_categories << "全部";
        m_categories << allCategories;
        
        // 更新分类下拉框
        if (m_categoryCombo) {
            m_categoryCombo->clear();
            m_categoryCombo->addItems(m_categories);
        }
        
        // 加载数据
        loadMenuData();
        
    } catch (const std::exception &e) {
        QMessageBox::warning(this, "加载失败", 
            QString("加载菜单数据失败: %1").arg(e.what()));
    }
    
    // 隐藏加载状态
    if (m_loadingBar) {
        m_loadingBar->setVisible(false);
    }
    if (m_loadingLabel) {
        m_loadingLabel->setVisible(false);
    }
    
    // 重新启用界面
    setUIEnabled(true);
}

void CustomerMenuUI::setCurrentUserId(int userId)
{
    m_currentUserId = userId;
}

void CustomerMenuUI::handleSearch()
{
    if (!m_searchEdit) return;
    
    m_currentSearchText = m_searchEdit->text().trimmed();
    m_currentPage = 1; // 重置到第一页
    loadMenuData();
}

void CustomerMenuUI::handleCategoryFilter()
{
    if (!m_categoryCombo) return;
    
    m_currentCategory = m_categoryCombo->currentText();
    m_currentPage = 1; // 重置到第一页
    loadMenuData();
}

void CustomerMenuUI::handlePriceSort()
{
    if (!m_sortCombo) return;
    
    m_currentSortOrder = m_sortCombo->currentText();
    loadMenuData();
}

void CustomerMenuUI::handleItemDetails()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;
    
    QString itemId = button->property("itemId").toString();
    
    // 查找菜品信息
    MenuItem item;
    bool found = false;
    for (const auto &menuItem : m_allMenuItems) {
        if (menuItem.id == itemId) {
            item = menuItem;
            found = true;
            break;
        }
    }
    
    if (found) {
        showItemDetailsDialog(item);
    }
}

void CustomerMenuUI::handleAddToCart()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;
    
    QString itemId = button->property("itemId").toString();
    
    // 查找菜品信息
    MenuItem item;
    bool found = false;
    for (const auto &menuItem : m_allMenuItems) {
        if (menuItem.id == itemId) {
            item = menuItem;
            found = true;
            break;
        }
    }
    
    if (found) {
        // 检查库存
        if (item.stock <= 0) {
            QMessageBox::warning(this, "库存不足", "该菜品暂时缺货");
            return;
        }
        
        // 显示详情对话框进行数量选择
        showItemDetailsDialog(item);
    }
}

void CustomerMenuUI::handlePageNavigation()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;
    
    if (button == m_prevButton && m_currentPage > 1) {
        m_currentPage--;
    } else if (button == m_nextButton && m_currentPage < m_totalPages) {
        m_currentPage++;
    }
    
    loadMenuData();
}

void CustomerMenuUI::clearSearch()
{
    if (m_searchEdit) {
        m_searchEdit->clear();
    }
    
    m_currentSearchText.clear();
    m_currentPage = 1;
    loadMenuData();
}

void CustomerMenuUI::refreshData()
{
    refreshMenuData();
}

void CustomerMenuUI::initializeUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(10, 10, 10, 10);
    m_mainLayout->setSpacing(10);
    
    // 创建各个区域
    createSearchArea();
    createFilterArea();
    createMenuDisplayArea();
    createPaginationArea();
}

void CustomerMenuUI::createSearchArea()
{
    // 搜索区域
    QGroupBox *searchGroup = new QGroupBox("搜索菜品", this);
    m_searchLayout = new QHBoxLayout(searchGroup);
    
    m_searchEdit = new QLineEdit(this);
    m_searchEdit->setPlaceholderText("请输入菜品名称、描述或关键词");
    m_searchEdit->setObjectName("searchEdit");
    
    m_searchButton = new QPushButton("搜索", this);
    m_searchButton->setObjectName("searchButton");
    
    m_clearButton = new QPushButton("清除", this);
    m_clearButton->setObjectName("clearButton");
    
    // 连接信号
    connect(m_searchEdit, &QLineEdit::returnPressed, this, &CustomerMenuUI::handleSearch);
    connect(m_searchButton, &QPushButton::clicked, this, &CustomerMenuUI::handleSearch);
    connect(m_clearButton, &QPushButton::clicked, this, &CustomerMenuUI::clearSearch);
    
    m_searchLayout->addWidget(m_searchEdit);
    m_searchLayout->addWidget(m_searchButton);
    m_searchLayout->addWidget(m_clearButton);
    
    m_mainLayout->addWidget(searchGroup);
}

void CustomerMenuUI::createFilterArea()
{
    // 过滤区域
    QGroupBox *filterGroup = new QGroupBox("筛选和排序", this);
    m_filterLayout = new QHBoxLayout(filterGroup);
    
    // 分类过滤
    QLabel *categoryLabel = new QLabel("分类:", this);
    m_categoryCombo = new QComboBox(this);
    m_categoryCombo->setObjectName("categoryCombo");
    m_categoryCombo->addItem("全部");
    
    // 排序选择
    QLabel *sortLabel = new QLabel("排序:", this);
    m_sortCombo = new QComboBox(this);
    m_sortCombo->setObjectName("sortCombo");
    m_sortCombo->addItems({"默认", "价格从低到高", "价格从高到低", "热销优先"});
    
    // 结果显示
    m_resultLabel = new QLabel("共 0 个菜品", this);
    m_resultLabel->setObjectName("resultLabel");
    
    // 查看购物车按钮
    m_viewCartButton = new QPushButton("🛒 查看购物车", this);
    m_viewCartButton->setObjectName("viewCartButton");
    
    // 连接信号
    connect(m_categoryCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &CustomerMenuUI::handleCategoryFilter);
    connect(m_sortCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &CustomerMenuUI::handlePriceSort);
    connect(m_viewCartButton, &QPushButton::clicked, this, &CustomerMenuUI::handleViewCart);
    
    m_filterLayout->addWidget(categoryLabel);
    m_filterLayout->addWidget(m_categoryCombo);
    m_filterLayout->addWidget(sortLabel);
    m_filterLayout->addWidget(m_sortCombo);
    m_filterLayout->addStretch();
    m_filterLayout->addWidget(m_resultLabel);
    m_filterLayout->addWidget(m_viewCartButton);
    
    m_mainLayout->addWidget(filterGroup);
}

void CustomerMenuUI::createMenuDisplayArea()
{
    // 加载状态指示器
    m_loadingLabel = new QLabel("正在加载菜单数据...", this);
    m_loadingLabel->setAlignment(Qt::AlignCenter);
    m_loadingLabel->setObjectName("loadingLabel");
    m_loadingLabel->setVisible(false);
    
    m_loadingBar = new QProgressBar(this);
    m_loadingBar->setObjectName("loadingBar");
    m_loadingBar->setVisible(false);
    
    // 菜单显示区域
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setObjectName("menuScrollArea");
    
    m_menuContainer = new QWidget();
    m_menuContainer->setObjectName("menuContainer");
    
    m_menuLayout = new QGridLayout(m_menuContainer);
    m_menuLayout->setSpacing(15);
    m_menuLayout->setContentsMargins(10, 10, 10, 10);
    
    m_scrollArea->setWidget(m_menuContainer);
    
    m_mainLayout->addWidget(m_loadingLabel);
    m_mainLayout->addWidget(m_loadingBar);
    m_mainLayout->addWidget(m_scrollArea);
}

void CustomerMenuUI::createPaginationArea()
{
    // 分页区域
    QGroupBox *paginationGroup = new QGroupBox("分页导航", this);
    m_paginationLayout = new QHBoxLayout(paginationGroup);
    
    m_prevButton = new QPushButton("上一页", this);
    m_prevButton->setObjectName("prevButton");
    m_prevButton->setEnabled(false);
    
    m_pageLabel = new QLabel("第 1 页 / 共 1 页", this);
    m_pageLabel->setAlignment(Qt::AlignCenter);
    m_pageLabel->setObjectName("pageLabel");
    
    m_nextButton = new QPushButton("下一页", this);
    m_nextButton->setObjectName("nextButton");
    m_nextButton->setEnabled(false);
    
    // 每页显示数量
    QLabel *pageSizeLabel = new QLabel("每页显示:", this);
    m_pageSizeCombo = new QComboBox(this);
    m_pageSizeCombo->setObjectName("pageSizeCombo");
    m_pageSizeCombo->addItems({"6", "12", "18", "24"});
    m_pageSizeCombo->setCurrentText(QString::number(m_pageSize));
    
    // 连接信号
    connect(m_prevButton, &QPushButton::clicked, this, &CustomerMenuUI::handlePageNavigation);
    connect(m_nextButton, &QPushButton::clicked, this, &CustomerMenuUI::handlePageNavigation);
    connect(m_pageSizeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            [this]() {
                m_pageSize = m_pageSizeCombo->currentText().toInt();
                m_currentPage = 1;
                loadMenuData();
            });
    
    m_paginationLayout->addWidget(m_prevButton);
    m_paginationLayout->addStretch();
    m_paginationLayout->addWidget(m_pageLabel);
    m_paginationLayout->addStretch();
    m_paginationLayout->addWidget(m_nextButton);
    m_paginationLayout->addWidget(pageSizeLabel);
    m_paginationLayout->addWidget(m_pageSizeCombo);
    
    m_mainLayout->addWidget(paginationGroup);
}

void CustomerMenuUI::applyStyleSheet()
{
    setStyleSheet(R"(
        CustomerMenuUI {
            background-color: #f8f9fa;
            font-family: "DejaVu Sans", "SimSun", "Microsoft YaHei";
        }
        
        QGroupBox {
            font-size: 14px;
            font-weight: bold;
            color: #2c3e50;
            border: 2px solid #bdc3c7;
            border-radius: 8px;
            margin-top: 10px;
            padding-top: 10px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 5px 0 5px;
            background-color: #f8f9fa;
        }
        
        #searchEdit {
            font-size: 13px;
            padding: 8px;
            border: 2px solid #bdc3c7;
            border-radius: 4px;
            background-color: white;
        }
        
        #searchEdit:focus {
            border-color: #3498db;
        }
        
        #searchButton, #clearButton {
            font-size: 13px;
            font-weight: bold;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 8px 20px;
            min-width: 80px;
        }
        
        #searchButton {
            background-color: #3498db;
        }
        
        #searchButton:hover {
            background-color: #2980b9;
        }
        
        #clearButton {
            background-color: #95a5a6;
        }
        
        #clearButton:hover {
            background-color: #7f8c8d;
        }
        
        #categoryCombo, #sortCombo, #pageSizeCombo {
            font-size: 13px;
            padding: 5px;
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            background-color: white;
            min-width: 120px;
        }
        
        #resultLabel, #pageLabel {
            font-size: 13px;
            color: #34495e;
        }
        
        #menuScrollArea {
            border: 1px solid #bdc3c7;
            border-radius: 5px;
            background-color: white;
        }
        
        #menuContainer {
            background-color: white;
        }
        
        #prevButton, #nextButton {
            font-size: 13px;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 8px 15px;
            background-color: #3498db;
        }
        
        #prevButton:hover, #nextButton:hover {
            background-color: #2980b9;
        }
        
        #prevButton:disabled, #nextButton:disabled {
            background-color: #bdc3c7;
        }
        
        #loadingLabel {
            font-size: 16px;
            color: #7f8c8d;
            font-style: italic;
        }
        
        #loadingBar {
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            background-color: #ecf0f1;
        }
        
        .menuItemCard {
            background-color: white;
            border: 1px solid #e0e6ed;
            border-radius: 8px;
            padding: 10px;
        }
        
        .menuItemCard:hover {
            border-color: #3498db;
        }
        
        .itemName {
            font-size: 15px;
            font-weight: bold;
            color: #2c3e50;
            background-color: transparent;
            padding: 3px 0px;
            margin-bottom: 3px;
        }
        
        .itemDescription {
            font-size: 12px;
            color: #7f8c8d;
            margin-bottom: 8px;
        }
        
        .itemPrice {
            font-size: 18px;
            font-weight: bold;
            color: #e74c3c;
            margin-bottom: 5px;
        }
        
        .itemCategory {
            font-size: 11px;
            color: #34495e;
            background-color: #ecf0f1;
            padding: 2px 6px;
            border-radius: 3px;
        }
        
        .itemStock {
            font-size: 11px;
            color: #27ae60;
        }
        
        .itemSales {
            font-size: 11px;
            color: #f39c12;
            margin-right: 8px;
        }
        
        .itemButton {
            font-size: 12px;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            margin: 2px;
        }
        
        .detailsButton {
            background-color: #3498db;
        }
        
        .detailsButton:hover {
            background-color: #2980b9;
        }
        
        .addButton {
            background-color: #27ae60;
        }
        
        .addButton:hover {
            background-color: #229954;
        }
        
        .addButton:disabled {
            background-color: #95a5a6;
        }
    )");
}

void CustomerMenuUI::loadMenuData()
{
    // 过滤菜单项
    m_filteredItems = filterMenuItems();
    
    // 计算分页信息
    int totalItems = m_filteredItems.size();
    m_totalPages = std::max(1, (int)std::ceil((double)totalItems / m_pageSize));
    
    if (m_currentPage > m_totalPages) {
        m_currentPage = m_totalPages;
    }
    
    // 更新结果标签
    if (m_resultLabel) {
        m_resultLabel->setText(QString("共 %1 个菜品").arg(totalItems));
    }
    
    // 获取当前页的菜单项
    int startIndex = (m_currentPage - 1) * m_pageSize;
    int endIndex = std::min(startIndex + m_pageSize, totalItems);
    
    QList<MenuItem> pageItems;
    for (int i = startIndex; i < endIndex; ++i) {
        pageItems.append(m_filteredItems[i]);
    }
    
    // 显示菜单项
    displayMenuItems(pageItems);
    
    // 更新分页信息
    updatePaginationInfo();
}

void CustomerMenuUI::displayMenuItems(const QList<MenuItem> &items)
{
    // 清除现有项目
    QLayoutItem *child;
    while ((child = m_menuLayout->takeAt(0)) != nullptr) {
        if (child->widget()) {
            child->widget()->deleteLater();
        }
        delete child;
    }
    
    // 显示菜单项
    int row = 0, col = 0;
    int columns = 3; // 每行3个菜品卡片
    
    for (const auto &item : items) {
        QWidget *card = createMenuItemCard(item);
        m_menuLayout->addWidget(card, row, col);
        
        col++;
        if (col >= columns) {
            col = 0;
            row++;
        }
    }
    
    // 如果没有菜品，显示提示
    if (items.isEmpty()) {
        QLabel *emptyLabel = new QLabel("没有找到符合条件的菜品", this);
        emptyLabel->setAlignment(Qt::AlignCenter);
        emptyLabel->setObjectName("emptyLabel");
        emptyLabel->setStyleSheet("color: #7f8c8d; font-size: 16px; padding: 50px;");
        m_menuLayout->addWidget(emptyLabel, 0, 0, 1, columns);
    }
}

QWidget* CustomerMenuUI::createMenuItemCard(const MenuItem &item)
{
    QFrame *card = new QFrame(this);
    card->setObjectName(QString("card_%1").arg(item.id));  // 设置唯一的objectName
    card->setProperty("class", "menuItemCard");
    card->setFixedSize(320, 280);  // 增加卡片尺寸，让布局更宽松
    
    QVBoxLayout *layout = new QVBoxLayout(card);
    layout->setContentsMargins(12, 12, 12, 12);  // 增加内边距
    layout->setSpacing(8);  // 增加元素间距
    
    // 菜品图片
    QLabel *imageLabel = new QLabel(card);
    imageLabel->setObjectName("imageLabel");
    imageLabel->setFixedSize(280, 140);  // 增加图片尺寸以适应更大的卡片
    imageLabel->setAlignment(Qt::AlignCenter);
    imageLabel->setStyleSheet("QLabel { border: 1px solid #e0e6ed; border-radius: 6px; background-color: #f8f9fa; }");
    
    // 加载菜品图片
    QString imagePath = item.imageUrl;
    

    
    // 先尝试加载菜品图片
    bool imageLoaded = false;
    if (!imagePath.isEmpty() && QFile::exists(imagePath)) {
        QPixmap pixmap(imagePath);
        if (!pixmap.isNull()) {
            // 缩放图片以适应标签大小，保持宽高比
            QPixmap scaledPixmap = pixmap.scaled(280, 140, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            imageLabel->setPixmap(scaledPixmap);
            imageLoaded = true;
        }
    }
    
    // 如果没有加载成功，使用白米饭图片作为通用默认图片
    if (!imageLoaded) {
        QString defaultImagePath = "resources/images/menu_items/default/default_food_240x120.png";
        if (QFile::exists(defaultImagePath)) {
            QPixmap pixmap(defaultImagePath);
            if (!pixmap.isNull()) {
                QPixmap scaledPixmap = pixmap.scaled(280, 140, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                imageLabel->setPixmap(scaledPixmap);
                imageLoaded = true;
                qDebug() << "Loaded default image (white rice):" << defaultImagePath;
            }
        }
    }
    
    // 最后的兜底方案：显示文字占位符
    if (!imageLoaded) {
        imageLabel->setText("🍽️\n" + item.name);
        imageLabel->setStyleSheet("QLabel { border: 1px solid #e0e6ed; border-radius: 6px; background-color: #f8f9fa; color: #7f8c8d; font-size: 12px; text-align: center; }");
        qDebug() << "Using text placeholder for:" << item.name;
    }
    
    // 菜品名称（放在卡片上方）
    QLabel *nameLabel = new QLabel(item.name, card);
    nameLabel->setProperty("class", "itemName");
    nameLabel->setWordWrap(true);
    nameLabel->setMaximumHeight(28);  // 增加名称高度，让长名称有更多空间
    nameLabel->setAlignment(Qt::AlignCenter);
    
    // 价格
    QLabel *priceLabel = new QLabel(QString("¥%1").arg(item.price, 0, 'f', 2), card);
    priceLabel->setProperty("class", "itemPrice");
    
    // 分类和库存信息
    QHBoxLayout *infoLayout = new QHBoxLayout();
    infoLayout->setSpacing(8);  // 增加信息区间距
    
    QLabel *categoryLabel = new QLabel(item.category, card);
    categoryLabel->setProperty("class", "itemCategory");
    
    // 销量信息
    QLabel *salesLabel = new QLabel(QString("销量: %1").arg(item.salesCount), card);
    salesLabel->setObjectName("salesLabel");  // 设置objectName用于查找
    salesLabel->setProperty("class", "itemSales");
    
    QLabel *stockLabel = new QLabel(QString("库存: %1").arg(item.stock), card);
    stockLabel->setObjectName("stockLabel");  // 设置objectName用于查找
    stockLabel->setProperty("class", "itemStock");
    
    infoLayout->addWidget(categoryLabel);
    infoLayout->addStretch();
    infoLayout->addWidget(salesLabel);
    infoLayout->addWidget(stockLabel);
    
    // 按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(10);  // 增加按钮间距
    
    QPushButton *detailsButton = new QPushButton("详情", card);
    detailsButton->setProperty("class", "itemButton detailsButton");
    detailsButton->setProperty("itemId", item.id);
    connect(detailsButton, &QPushButton::clicked, this, &CustomerMenuUI::handleItemDetails);
    
    QPushButton *addButton = new QPushButton("加入购物车", card);
    addButton->setObjectName("addButton");  // 设置objectName用于查找
    addButton->setProperty("class", "itemButton addButton");
    addButton->setProperty("itemId", item.id);
    addButton->setEnabled(item.stock > 0);
    connect(addButton, &QPushButton::clicked, this, &CustomerMenuUI::handleAddToCart);
    
    buttonLayout->addWidget(detailsButton);
    buttonLayout->addWidget(addButton);
    
    // 添加到布局
    layout->addWidget(nameLabel);
    layout->addWidget(imageLabel);
    layout->addWidget(priceLabel);
    layout->addLayout(infoLayout);
    layout->addStretch();
    layout->addLayout(buttonLayout);
    
    return card;
}

QList<MenuItem> CustomerMenuUI::filterMenuItems()
{
    QList<MenuItem> filtered = m_allMenuItems;
    
    // 搜索过滤
    if (!m_currentSearchText.isEmpty()) {
        QList<MenuItem> searchFiltered;
        for (const auto &item : filtered) {
            if (item.name.contains(m_currentSearchText, Qt::CaseInsensitive) ||
                item.description.contains(m_currentSearchText, Qt::CaseInsensitive)) {
                searchFiltered.append(item);
            }
        }
        filtered = searchFiltered;
    }
    
    // 分类过滤
    if (m_currentCategory != "全部") {
        QList<MenuItem> categoryFiltered;
        for (const auto &item : filtered) {
            if (item.category == m_currentCategory) {
                categoryFiltered.append(item);
            }
        }
        filtered = categoryFiltered;
    }
    
    // 排序
    if (m_currentSortOrder == "价格从低到高") {
        std::sort(filtered.begin(), filtered.end(), 
                  [](const MenuItem &a, const MenuItem &b) {
                      return a.price < b.price;
                  });
    } else if (m_currentSortOrder == "价格从高到低") {
        std::sort(filtered.begin(), filtered.end(), 
                  [](const MenuItem &a, const MenuItem &b) {
                      return a.price > b.price;
                  });
    } else if (m_currentSortOrder == "热销优先") {
        std::sort(filtered.begin(), filtered.end(), 
                  [](const MenuItem &a, const MenuItem &b) {
                      return a.salesCount > b.salesCount;
                  });
    }
    
    return filtered;
}

void CustomerMenuUI::updatePaginationInfo()
{
    // 更新页面标签
    if (m_pageLabel) {
        m_pageLabel->setText(QString("第 %1 页 / 共 %2 页").arg(m_currentPage).arg(m_totalPages));
    }
    
    // 更新按钮状态
    if (m_prevButton) {
        m_prevButton->setEnabled(m_currentPage > 1);
    }
    if (m_nextButton) {
        m_nextButton->setEnabled(m_currentPage < m_totalPages);
    }
}

void CustomerMenuUI::showItemDetailsDialog(const MenuItem &item)
{
    MenuItemDetailsDialog dialog(item, this);
    
    connect(&dialog, &MenuItemDetailsDialog::addToCartRequested,
            [this, item](int quantity) {
                emit addToCartRequested(item.id, quantity);
                // 移除这里的成功提示，因为购物车的addItemToCart方法已经处理了所有反馈
            });
    
    dialog.exec();
}

void CustomerMenuUI::setUIEnabled(bool enabled)
{
    if (m_searchEdit) m_searchEdit->setEnabled(enabled);
    if (m_searchButton) m_searchButton->setEnabled(enabled);
    if (m_clearButton) m_clearButton->setEnabled(enabled);
    if (m_categoryCombo) m_categoryCombo->setEnabled(enabled);
    if (m_sortCombo) m_sortCombo->setEnabled(enabled);
    if (m_prevButton) m_prevButton->setEnabled(enabled && m_currentPage > 1);
    if (m_nextButton) m_nextButton->setEnabled(enabled && m_currentPage < m_totalPages);
    if (m_pageSizeCombo) m_pageSizeCombo->setEnabled(enabled);
}

// MenuItemDetailsDialog 实现

MenuItemDetailsDialog::MenuItemDetailsDialog(const MenuItem &item, QWidget *parent)
    : QDialog(parent)
    , m_menuItem(item)
    , m_mainLayout(nullptr)
    , m_scrollArea(nullptr)
    , m_contentWidget(nullptr)
    , m_contentLayout(nullptr)
    , m_nameLabel(nullptr)
    , m_descriptionLabel(nullptr)
    , m_priceLabel(nullptr)
    , m_categoryLabel(nullptr)
    , m_salesLabel(nullptr)
    , m_stockLabel(nullptr)
    , m_decreaseButton(nullptr)
    , m_quantityLabel(nullptr)
    , m_increaseButton(nullptr)
    , m_currentQuantity(1)
    , m_addButton(nullptr)
    , m_cancelButton(nullptr)
{
    initializeUI();
    applyStyleSheet();
}

int MenuItemDetailsDialog::getSelectedQuantity() const
{
    return m_currentQuantity;
}

void MenuItemDetailsDialog::handleAddToCart()
{
    // 首先检查库存
    if (m_menuItem.stock <= 0) {
        QMessageBox::warning(this, "库存不足", "该商品暂无库存，无法添加到购物车");
        return;
    }
    
    int quantity = getSelectedQuantity();
    if (quantity <= 0) {
        QMessageBox::warning(this, "数量错误", "请选择有效的数量");
        return;
    }
    
    if (quantity > m_menuItem.stock) {
        QMessageBox::warning(this, "库存不足", 
            QString("选择的数量(%1)超过了库存数量(%2)，请调整数量").arg(quantity).arg(m_menuItem.stock));
        return;
    }
    
    emit addToCartRequested(quantity);
    accept();
}

void MenuItemDetailsDialog::initializeUI()
{
    setWindowTitle("菜品详情");
    setFixedSize(500, 700);  // 增加对话框尺寸以适应滚动布局
    setModal(true);
    
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(15, 15, 15, 15);
    m_mainLayout->setSpacing(10);
    
    // 菜品图片 - 置顶固定
    QLabel *imageLabel = new QLabel(this);
    imageLabel->setFixedSize(450, 220);  // 增加图片尺寸
    imageLabel->setAlignment(Qt::AlignCenter);
    imageLabel->setStyleSheet("QLabel { border: 1px solid #e0e6ed; border-radius: 8px; background-color: #f8f9fa; }");
    
    // 加载菜品图片
    QString imagePath = m_menuItem.imageUrl;
    
    // 先尝试加载菜品图片
    bool imageLoaded = false;
    if (!imagePath.isEmpty() && QFile::exists(imagePath)) {
        QPixmap pixmap(imagePath);
        if (!pixmap.isNull()) {
            // 缩放图片以适应标签大小，保持宽高比
            QPixmap scaledPixmap = pixmap.scaled(450, 220, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            imageLabel->setPixmap(scaledPixmap);
            imageLoaded = true;
        }
    }
    
    // 如果没有加载成功，使用白米饭图片作为通用默认图片
    if (!imageLoaded) {
        QString defaultImagePath = "resources/images/menu_items/default/default_food_240x120.png";
        if (QFile::exists(defaultImagePath)) {
            QPixmap pixmap(defaultImagePath);
            if (!pixmap.isNull()) {
                QPixmap scaledPixmap = pixmap.scaled(450, 220, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                imageLabel->setPixmap(scaledPixmap);
                imageLoaded = true;
            }
        }
    }
    
    // 最后的兜底方案：显示文字占位符
    if (!imageLoaded) {
        imageLabel->setText("🍽️\n" + m_menuItem.name + "\n详细图片");
        imageLabel->setStyleSheet("QLabel { border: 1px solid #e0e6ed; border-radius: 8px; background-color: #f8f9fa; color: #7f8c8d; font-size: 14px; text-align: center; }");
    }
    
    // 创建滚动区域
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setStyleSheet("QScrollArea { border: none; background-color: transparent; }");
    
    // 创建内容容器
    m_contentWidget = new QWidget();
    m_contentLayout = new QVBoxLayout(m_contentWidget);
    m_contentLayout->setContentsMargins(10, 10, 10, 10);
    m_contentLayout->setSpacing(12);
    
    // 菜品信息
    m_nameLabel = new QLabel(m_menuItem.name, m_contentWidget);
    m_nameLabel->setObjectName("itemName");
    m_nameLabel->setAlignment(Qt::AlignCenter);
    m_nameLabel->setStyleSheet("font-size: 18px; font-weight: bold; color: #2c3e50; margin-bottom: 10px;");
    
    // 菜品介绍 - 独立显示区域
    m_descriptionLabel = new QLabel(m_menuItem.description, m_contentWidget);
    m_descriptionLabel->setObjectName("itemDescription");
    m_descriptionLabel->setWordWrap(true);
    m_descriptionLabel->setStyleSheet("font-size: 14px; color: #34495e; line-height: 1.5; padding: 10px; background-color: #f8f9fa; border-radius: 6px; border: 1px solid #e9ecef;");
    m_descriptionLabel->setMinimumHeight(60);
    
    // 菜品详细信息
    m_priceLabel = new QLabel(QString("价格: ¥%1").arg(m_menuItem.price, 0, 'f', 2), m_contentWidget);
    m_priceLabel->setObjectName("itemPrice");
    m_priceLabel->setStyleSheet("font-size: 16px; font-weight: bold; color: #e74c3c;");
    
    m_categoryLabel = new QLabel(QString("分类: %1").arg(m_menuItem.category), m_contentWidget);
    m_categoryLabel->setObjectName("itemCategory");
    m_categoryLabel->setStyleSheet("font-size: 14px; color: #34495e;");
    
    m_salesLabel = new QLabel(QString("销量: %1").arg(m_menuItem.salesCount), m_contentWidget);
    m_salesLabel->setObjectName("itemSales");
    m_salesLabel->setStyleSheet("font-size: 14px; color: #f39c12;");
    
    m_stockLabel = new QLabel(QString("库存: %1").arg(m_menuItem.stock), m_contentWidget);
    m_stockLabel->setObjectName("itemStock");
    m_stockLabel->setStyleSheet("font-size: 14px; color: #27ae60;");
    
    // 数量选择
    QHBoxLayout *quantityLayout = new QHBoxLayout();
    QLabel *quantityLabel = new QLabel("数量:", m_contentWidget);
    quantityLabel->setStyleSheet("font-size: 14px; color: #2c3e50;");
    
    // 数量控制按钮组
    m_decreaseButton = new QPushButton("-", m_contentWidget);
    m_decreaseButton->setFixedSize(30, 30);
    m_decreaseButton->setStyleSheet("QPushButton { background-color: #dc3545; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
    m_decreaseButton->setToolTip("减少数量");
    
    m_quantityLabel = new QLabel(QString::number(m_currentQuantity), m_contentWidget);
    m_quantityLabel->setFixedWidth(50);
    m_quantityLabel->setAlignment(Qt::AlignCenter);
    m_quantityLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: bold; color: #2c3e50; background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px; padding: 4px; }");
    
    m_increaseButton = new QPushButton("+", m_contentWidget);
    m_increaseButton->setFixedSize(30, 30);
    m_increaseButton->setStyleSheet("QPushButton { background-color: #28a745; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
    m_increaseButton->setToolTip("增加数量");
    
    // 连接信号
    connect(m_decreaseButton, &QPushButton::clicked, this, &MenuItemDetailsDialog::handleDecreaseQuantity);
    connect(m_increaseButton, &QPushButton::clicked, this, &MenuItemDetailsDialog::handleIncreaseQuantity);
    
    // 更新按钮状态
    updateQuantityControls();
    
    quantityLayout->addWidget(quantityLabel);
    quantityLayout->addStretch();
    quantityLayout->addWidget(m_decreaseButton);
    quantityLayout->addWidget(m_quantityLabel);
    quantityLayout->addWidget(m_increaseButton);
    
    // 添加到内容布局
    m_contentLayout->addWidget(m_nameLabel);
    m_contentLayout->addWidget(m_descriptionLabel);
    m_contentLayout->addWidget(m_priceLabel);
    m_contentLayout->addWidget(m_categoryLabel);
    m_contentLayout->addWidget(m_salesLabel);
    m_contentLayout->addWidget(m_stockLabel);
    m_contentLayout->addLayout(quantityLayout);
    m_contentLayout->addStretch();
    
    // 设置滚动区域的内容
    m_scrollArea->setWidget(m_contentWidget);
    
    // 按钮区域 - 固定在底部
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    m_addButton = new QPushButton("加入购物车", this);
    m_addButton->setObjectName("addButton");
    m_addButton->setStyleSheet("QPushButton { background-color: #007bff; color: white; border: none; border-radius: 6px; padding: 8px 16px; font-size: 14px; font-weight: bold; } QPushButton:hover { background-color: #0056b3; }");
    
    m_cancelButton = new QPushButton("取消", this);
    m_cancelButton->setObjectName("cancelButton");
    m_cancelButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 6px; padding: 8px 16px; font-size: 14px; } QPushButton:hover { background-color: #545b62; }");
    
    connect(m_addButton, &QPushButton::clicked, this, &MenuItemDetailsDialog::handleAddToCart);
    connect(m_cancelButton, &QPushButton::clicked, this, &QDialog::reject);
    
    buttonLayout->addWidget(m_addButton);
    buttonLayout->addWidget(m_cancelButton);
    
    // 主布局：图片置顶，滚动区域居中，按钮固定底部
    m_mainLayout->addWidget(imageLabel);
    m_mainLayout->addWidget(m_scrollArea);
    m_mainLayout->addLayout(buttonLayout);
    
    // 检查库存状态，如果库存为0则禁用加入购物车按钮
    updateAddToCartButtonState();
}

void MenuItemDetailsDialog::applyStyleSheet()
{
    setStyleSheet(R"(
        QDialog {
            background-color: #f8f9fa;
            font-family: "DejaVu Sans", "SimSun", "Microsoft YaHei";
        }
        
        #itemName {
            font-size: 20px;
            font-weight: bold;
            color: #2c3e50;
            background-color: transparent;
        }
        
        #itemDescription {
            font-size: 14px;
            color: #34495e;
        }
        
        #itemPrice {
            font-size: 18px;
            font-weight: bold;
            color: #e74c3c;
        }
        
        #itemCategory, #itemStock {
            font-size: 13px;
            color: #7f8c8d;
        }
        

        
        #addButton, #cancelButton {
            font-size: 13px;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 8px 20px;
            min-width: 100px;
        }
        
        #addButton {
            background-color: #27ae60;
        }
        
        #addButton:hover {
            background-color: #229954;
        }
        
        #cancelButton {
            background-color: #95a5a6;
        }
        
        #cancelButton:hover {
            background-color: #7f8c8d;
        }
    )");
}

void MenuItemDetailsDialog::handleIncreaseQuantity()
{
    if (m_currentQuantity < m_menuItem.stock) {
        m_currentQuantity++;
        updateQuantityControls();
    }
}

void MenuItemDetailsDialog::handleDecreaseQuantity()
{
    if (m_currentQuantity > 1) {
        m_currentQuantity--;
        updateQuantityControls();
    }
}

void MenuItemDetailsDialog::updateQuantityControls()
{
    // 更新数量显示
    if (m_quantityLabel) {
        m_quantityLabel->setText(QString::number(m_currentQuantity));
        
        // 更新工具提示
        if (m_menuItem.stock <= 0) {
            m_quantityLabel->setToolTip("该商品暂无库存");
        } else if (m_currentQuantity >= m_menuItem.stock) {
            m_quantityLabel->setToolTip(QString("已达到最大库存限制 (%1)").arg(m_menuItem.stock));
        } else {
            m_quantityLabel->setToolTip(QString("当前数量：%1，库存：%2件").arg(m_currentQuantity).arg(m_menuItem.stock));
        }
    }
    
    // 如果库存为0，禁用所有数量控制按钮
    if (m_menuItem.stock <= 0) {
        if (m_decreaseButton) {
            m_decreaseButton->setEnabled(false);
            m_decreaseButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
        }
        if (m_increaseButton) {
            m_increaseButton->setEnabled(false);
            m_increaseButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
        }
        return;
    }
    
    // 更新减少按钮状态
    if (m_decreaseButton) {
        if (m_currentQuantity > 1) {
            m_decreaseButton->setEnabled(true);
            m_decreaseButton->setStyleSheet("QPushButton { background-color: #dc3545; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
        } else {
            m_decreaseButton->setEnabled(false);
            m_decreaseButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
        }
    }
    
    // 更新增加按钮状态
    if (m_increaseButton) {
        if (m_currentQuantity >= m_menuItem.stock) {
            m_increaseButton->setEnabled(false);
            m_increaseButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
            m_increaseButton->setToolTip("已达到最大库存限制");
        } else {
            m_increaseButton->setEnabled(true);
            m_increaseButton->setStyleSheet("QPushButton { background-color: #28a745; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
            m_increaseButton->setToolTip(QString("增加数量，库存还有%1件").arg(m_menuItem.stock - m_currentQuantity));
        }
    }
}

void MenuItemDetailsDialog::updateAddToCartButtonState()
{
    if (!m_addButton) return;
    
    if (m_menuItem.stock <= 0) {
        // 库存为0时禁用按钮并修改样式
        m_addButton->setEnabled(false);
        m_addButton->setText("暂无库存");
        m_addButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 6px; padding: 8px 16px; font-size: 14px; font-weight: bold; } QPushButton:hover { background-color: #6c757d; }");
        m_addButton->setToolTip("该商品暂无库存");
        
        // 同时禁用数量控制按钮
        if (m_increaseButton) {
            m_increaseButton->setEnabled(false);
            m_increaseButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
        }
        if (m_decreaseButton) {
            m_decreaseButton->setEnabled(false);
            m_decreaseButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 15px; font-weight: bold; font-size: 16px; }");
        }
    } else {
        // 有库存时启用按钮并恢复正常样式
        m_addButton->setEnabled(true);
        m_addButton->setText("加入购物车");
        m_addButton->setStyleSheet("QPushButton { background-color: #007bff; color: white; border: none; border-radius: 6px; padding: 8px 16px; font-size: 14px; font-weight: bold; } QPushButton:hover { background-color: #0056b3; }");
        m_addButton->setToolTip("点击加入购物车");
        
        // 恢复数量控制按钮状态（通过updateQuantityControls处理）
        updateQuantityControls();
    }
}

void CustomerMenuUI::handleViewCart()
{
    emit viewCartRequested();
}

void CustomerMenuUI::onStockUpdated(const QString& itemId, int oldStock, int newStock)
{
    Q_UNUSED(oldStock)
    
    // 更新显示的菜品库存状态
    updateMenuItemStock(itemId, newStock);
}

void CustomerMenuUI::onMenuItemUpdated(const MenuItem& item)
{
    // 更新内存中的菜品数据
    for (int i = 0; i < m_allMenuItems.size(); ++i) {
        if (m_allMenuItems[i].id == item.id) {
            m_allMenuItems[i] = item;
            break;
        }
    }
    
    // 如果菜品的分类发生了变化，可能需要重新加载分类列表
    if (!m_categories.contains(item.category)) {
        // 刷新分类列表
        refreshMenuData();
        return;
    }
    
    // 直接更新对应的菜品卡片，避免重新加载整个菜单
    updateMenuItemCard(item);
}

void CustomerMenuUI::updateMenuItemStock(const QString& itemId, int newStock)
{
    // 如果没有菜单容器或数据管理器，直接返回
    if (!m_menuContainer || !m_menuManager) {
        return;
    }
    
    // 遍历所有菜品卡片，找到对应的菜品并更新库存显示
    for (int i = 0; i < m_menuLayout->count(); ++i) {
        QWidget* card = m_menuLayout->itemAt(i)->widget();
        if (!card) continue;
        
        // 通过objectName获取菜品ID（需要在创建卡片时设置）
        if (card->objectName() == QString("card_%1").arg(itemId)) {
            // 找到对应的库存标签并更新
            QLabel* stockLabel = card->findChild<QLabel*>("stockLabel");
            if (stockLabel) {
                if (newStock > 0) {
                    stockLabel->setText(QString("库存: %1").arg(newStock));
                    stockLabel->setStyleSheet("color: #28a745; font-weight: bold;");
                } else {
                    stockLabel->setText("暂无库存");
                    stockLabel->setStyleSheet("color: #dc3545; font-weight: bold;");
                }
            }
            
            // 更新添加按钮状态
            QPushButton* addButton = card->findChild<QPushButton*>("addButton");
            if (addButton) {
                addButton->setEnabled(newStock > 0);
                if (newStock <= 0) {
                    addButton->setText("暂无库存");
                    addButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 5px; padding: 8px 15px; }");
                } else {
                    addButton->setText("加入购物车");
                    addButton->setStyleSheet("QPushButton { background-color: #007bff; color: white; border: none; border-radius: 5px; padding: 8px 15px; }");
                }
            }
            
            break;
        }
    }
}

void CustomerMenuUI::updateMenuItemCard(const MenuItem& item)
{
    // 如果没有菜单容器或布局，直接返回
    if (!m_menuContainer || !m_menuLayout) {
        return;
    }
    
    // 使用与updateMenuItemStock相同的方法查找卡片
    QWidget* card = nullptr;
    QString targetCardName = QString("card_%1").arg(item.id);
    
    for (int i = 0; i < m_menuLayout->count(); ++i) {
        QWidget* widget = m_menuLayout->itemAt(i)->widget();
        if (widget && widget->objectName() == targetCardName) {
            card = widget;
            break;
        }
    }
    
    if (!card) {
        // 如果找不到卡片，可能菜品不在当前显示的页面中，刷新整个菜单
        refreshMenuData();
        return;
    }
    
    // 更新菜品图片
    QLabel* imageLabel = card->findChild<QLabel*>("imageLabel");
    if (imageLabel) {
        QString imagePath = item.imageUrl;
        
        // 先尝试加载菜品图片
        bool imageLoaded = false;
        if (!imagePath.isEmpty() && QFile::exists(imagePath)) {
            QPixmap pixmap(imagePath);
            if (!pixmap.isNull()) {
                QPixmap scaledPixmap = pixmap.scaled(280, 140, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                imageLabel->setPixmap(scaledPixmap);
                imageLoaded = true;
            }
        }
        
        // 如果没有加载成功，使用白米饭图片作为通用默认图片
        if (!imageLoaded) {
            QString defaultImagePath = "resources/images/menu_items/default/default_food_240x120.png";
            if (QFile::exists(defaultImagePath)) {
                QPixmap pixmap(defaultImagePath);
                if (!pixmap.isNull()) {
                    QPixmap scaledPixmap = pixmap.scaled(280, 140, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                    imageLabel->setPixmap(scaledPixmap);
                    imageLoaded = true;
                }
            }
        }
        
        // 最后的兜底方案：显示文字占位符
        if (!imageLoaded) {
            imageLabel->setText("🍽️\n" + item.name);
            imageLabel->setStyleSheet("QLabel { border: 1px solid #e0e6ed; border-radius: 6px; background-color: #f8f9fa; color: #7f8c8d; font-size: 12px; text-align: center; }");
        }
    }
    
    // 更新菜品名称
    QLabel* nameLabel = nullptr;
    QList<QLabel*> labels = card->findChildren<QLabel*>();
    
    for (QLabel* label : labels) {
        if (label->property("class").toString().contains("itemName")) {
            nameLabel = label;
            break;
        }
    }
    if (nameLabel) {
        nameLabel->setText(item.name);
    }
    
    // 更新价格
    QLabel* priceLabel = nullptr;
    for (QLabel* label : labels) {
        if (label->property("class").toString().contains("itemPrice")) {
            priceLabel = label;
            break;
        }
    }
    if (priceLabel) {
        priceLabel->setText(QString("¥%1").arg(item.price, 0, 'f', 2));
    }
    
    // 更新分类
    QLabel* categoryLabel = nullptr;
    for (QLabel* label : labels) {
        if (label->property("class").toString().contains("itemCategory")) {
            categoryLabel = label;
            break;
        }
    }
    if (categoryLabel) {
        categoryLabel->setText(item.category);
    }
    
    // 更新销量
    QLabel* salesLabel = card->findChild<QLabel*>("salesLabel");
    if (salesLabel) {
        salesLabel->setText(QString("销量: %1").arg(item.salesCount));
    }
    
    // 更新库存
    QLabel* stockLabel = card->findChild<QLabel*>("stockLabel");
    if (stockLabel) {
        if (item.stock > 0) {
            stockLabel->setText(QString("库存: %1").arg(item.stock));
            stockLabel->setStyleSheet("color: #28a745; font-weight: bold;");
        } else {
            stockLabel->setText("暂无库存");
            stockLabel->setStyleSheet("color: #dc3545; font-weight: bold;");
        }
    }
    
    // 更新加入购物车按钮状态
    QPushButton* addButton = card->findChild<QPushButton*>("addButton");
    if (addButton) {
        addButton->setEnabled(item.stock > 0);
        if (item.stock <= 0) {
            addButton->setText("暂无库存");
            addButton->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 5px; padding: 8px 15px; }");
        } else {
            addButton->setText("加入购物车");
            addButton->setStyleSheet("QPushButton { background-color: #007bff; color: white; border: none; border-radius: 5px; padding: 8px 15px; }");
        }
    }
}

void CustomerMenuUI::onCategoriesChanged(const QStringList& categories)
{
    // 添加调试信息
    qDebug() << "CustomerMenuUI::onCategoriesChanged called with categories:" << categories;
    
    // 保存当前选中的分类
    QString currentCategory = m_currentCategory;
    
    // 更新分类列表
    m_categories.clear();
    m_categories << "全部";
    m_categories << categories;
    
    // 更新分类下拉框
    if (m_categoryCombo) {
        // 暂时断开信号连接，避免触发不必要的过滤
        m_categoryCombo->blockSignals(true);
        
        m_categoryCombo->clear();
        m_categoryCombo->addItems(m_categories);
        
        // 尝试恢复之前选中的分类
        int index = m_categories.indexOf(currentCategory);
        if (index >= 0) {
            m_categoryCombo->setCurrentIndex(index);
        } else {
            // 如果之前的分类不存在了，默认选择"全部"
            m_categoryCombo->setCurrentIndex(0);
            m_currentCategory = "全部";
        }
        
        // 重新连接信号
        m_categoryCombo->blockSignals(false);
    }
    
    // 重新过滤和显示菜单项（只有分类变化时才需要重新过滤）
    loadMenuData();
}

void CustomerMenuUI::onExternalFileChanged(DataType dataType, const QString& filePath)
{
    Q_UNUSED(filePath)
    
    // 当检测到菜单数据文件的外部变更时，刷新菜单数据
    if (dataType == DataType::MENU) {
        qDebug() << "CustomerMenuUI: External menu file changed, refreshing menu data";
        
        // 延迟刷新，确保文件写入完成
        QTimer::singleShot(100, this, [this]() {
            refreshMenuData();
        });
    }
}
